<?php

namespace app\erp\controller;


use app\admin\model\Synlogs;
use think\Log;

class Mater extends Base
{
    public function __construct($starttime, $endtime,$client_id,$client_secret,$account_id,$user_name)
    {
        parent::__construct($client_id, $client_secret,$account_id,$user_name);

        $this->starttime = $starttime;
        $this->endtime   = $endtime;
    }
    public function run($forg_fnumber,$forig_id,$page,$pageSize,$uuid)
    {
        $res = $this->getMaterialGroupPage($forg_fnumber,$page,$pageSize,$uuid);

        if($res['code'] === 1)
        {
            $response = $this->insertDataAndUpdateSuper($res['data'], $forig_id,$uuid);

            if($response)
            {                Synlogs::where('id',$uuid)->update([
                'fk_bdl_successnums' => $response['total'],
                'fk_bdl_status'      => "true",
                'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
            ]);
                Log::info('物料同步成功,'. "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forg_fnumber . "参数：" . json_encode($res['data']));

                return "组织编码".$forg_fnumber . ':本次成功同步条数' . $response['total'];

            }
        }elseif ($res['code'] === 2) {
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_successnums' => 0,
                'fk_bdl_status'      => "true",
                'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
            ]);
            return "组织编码".$forg_fnumber . ':本次成功同步条数0';

        }
    }
    private function getMaterialGroupPage($createorg_number, $pageNo, $pageSize,$uuid)
    {
        $method  = "v2/bdl/bdl_comm_basedata/bdl_bd_material/queryMaterial";

        $fullurl = $this->url . $method;

        Synlogs::where('id',$uuid)->update([
            'fk_bdl_url'        => $fullurl,

        ]);

        $response_data = [
            'data'      => [
                'starttime'             => $this->starttime,
                'endtime'               => $this->endtime,
                'createorg_number'      => $createorg_number,
            ],
            'pageNo'    => $pageNo,
            'pageSize'  => $pageSize,
        ];

        $this->curl->setHeader("Content-Type", "application/json");
        $this->curl->setHeader("accesstoken", $this->getToken());
        $this->curl->setHeader("Idempotency-Key", uuid());

        $res = $this->curl->post($fullurl, json_encode($response_data));


        if ($res && is_object($res) && $res->status == 1)
        {
            if($res->data->totalCount > 0){

                return [
                    'data'  => $res->data->rows,
                    'code'  => 1
                ];
            }else{
                return [
                    'code'  => 2,
                ];
            }

        }else{
            if(strlen($res->message) > 255)
            {
//                $res->message = substr($res->message,0,155);

                return $this->error('aaaaaaaa'  . request()->action() .  $res->message);

            }
            if(property_exists($res,'errorCode') && $res->errorCode == 404)
            {
                return $this->error('aaaaaaaa'  . request()->action() .  $res->message);
            }
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_exceptionmsg'   => $res->message,
                'fk_bdl_status'         => "false",
            ]);
            Log::error('获取物料失败：' . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $createorg_number . "参数：" . json_encode($response_data));

            return [
                'data' => false,
                'code' => 0
            ];
        }

    }

    private function insertDataAndUpdateSuper($data, $forgid,$uuid)
    {
        $count = 0;

        if(!empty($data))
        {
            try {
                // 组装 data 并插入
                foreach ($data as $k => $v)
                {

                    //判断是否已经存在
                    $isExist = \app\admin\model\Material::where('forgid',$forgid)->where('fnumber',$v->number)->where('fk_bdl_bd_datacenter',$this->account_id)->find();


                    $insertData = [
                        'fname'                             => $v->name,
                        'fnumber'                           => $v->number,
                        'fenable'                           => $v->enable,
                        'forgid'                            => $forgid,
                        'fk_bdl_createtime'                 => $v->createtime,
                        'fk_bdl_modifytime'                 => $v->modifytime,
                        'fk_bdl_issystem'                   => $v->bdl_issystem,
                        'fk_bdl_bd_datacenter'              => $this->account_id,
                        'fk_bdl_comment'                    => $v->group_number,
                        'fk_bdl_unitid'                     => !empty($v->bdl_unitid_name) ? $v->bdl_unitid_name : '无',
                        'fk_bdl_priceunitid'                => $v->bdl_priceunitid_name,
                        'fk_bdl_specification'              => $v->bdl_specification,
                        'fk_bdl_materialtype'               => $v->bdl_materialtype,
                        'fk_bdl_shortname'                  => $v->bdl_shortname,
                        'fk_bdl_model'                      => $v->bdl_model,
                        'fk_bdl_matnature'                  => $v->bdl_matnature,
                        'fk_bdl_matpropjsondata'            => json_encode($v->bdl_entry)
                    ];

                    if(!empty($isExist))
                    {

                        unset($insertData['forgid']);
                        unset($insertData['fk_bdl_bd_datacenter']);
                        \app\admin\model\Material::where('id',$isExist['id'])->update($insertData);

                    }else{
                        \app\admin\model\Material::create($insertData);

                    }
                    $count++;

                }

                //必须先更新分组 才能更新关联表
                $this->updateMaterCategory($forgid);
                $this->updateMaterialentryCategory($forgid);
            }catch (\Exception $e)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_exceptionmsg' => $e->getMessage(),
                    'fk_bdl_status'         => "false",
                ]);
                Log::error('物料更新失败：' .  $e->getMessage() . "时间：".date('Y-m-d H:i:s') . "组织ID："  . $forgid);

                $this->error('aaaaaaaa'  . request()->action() .  $e->getMessage());
            }


        }

        return [
            'code'      =>1,
            'total'     => $count,
        ];

    }


    //更新分组
    public function updateMaterCategory($forgid)
    {
        $data = \app\admin\model\Material::where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->select();

        foreach ($data as $k=>$v)
        {
            //fk_bdl_comment=fk_bdl_bdgroup编码
            if(!empty($v['fk_bdl_comment']))
            {
                $super = \app\admin\model\Materialcate::where('fnumber',$v['fk_bdl_comment'])->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                if($super)
                {
                    \app\admin\model\Material::where('id', $v['id'])->update(['fk_bdl_bdgroup' => $super['id']]);
                }
            }
        }
    }

    //更新分类的属性关联
    public function updateMaterialentryCategory($forgid)
    {
        $data = \app\admin\model\Material::where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->select();

        foreach ($data as $k=>$v)
        {
            if(!empty($v['fk_bdl_matpropjsondata']))
            {
                $materialentry_data = json_decode($v['fk_bdl_matpropjsondata'],true);

                if(!empty($materialentry_data))
                {
                    foreach ($materialentry_data as $key=>$value)
                    {
                        //组装tk_bdl_bd_materialentry所需要的数据
                        //查找属性id
                        $matpop = \app\admin\model\Matprop::where('fnumber',$value['bdl_bd_matprop_number'])->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                        if(!empty($matpop))
                        {
                            $fk_bdl_bd_material_g = $v['fk_bdl_bdgroup'];
                            $fk_bdl_bd_matprop    = $matpop['id'];

                            //查找是否存在 分类id 属性id 组织id 数据中心编码
                            $isExist = \app\admin\model\Materialentry::where('fk_bdl_bd_material_g',$fk_bdl_bd_material_g)->where('fk_bdl_bd_matprop',$fk_bdl_bd_matprop)->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                            $insertData = [
                                'fk_bdl_bd_material_g'  => $fk_bdl_bd_material_g,
                                'fk_bdl_bd_matprop'     => $fk_bdl_bd_matprop,
                                'forgid'                => $forgid,
                                'fk_bdl_bd_datacenter'  => $this->account_id,
                            ];

                            if(!empty($isExist))
                            {
                                \app\admin\model\Materialentry::where('id',$isExist['id'])->update($insertData);
                            }else{
                                \app\admin\model\Materialentry::create($insertData);
                            }
                        }
                    }

                }

            }

        }
    }
}